#!/usr/bin/python

import os
import sys
import signal

pid_file = "guowu.pid"
log_file = "guowu.log"

def start():
    if os.path.exists(pid_file):
        print ("A daemon is running already.")
        return -1
    
    pid = os.fork()
    if pid == 0:
        try:
            pid = os.getpid()
            os.setpgid(pid, pid)
            with open(pid_file, "w") as pidfp:
                pidfp.write("{0}".format(pid))
            os.system("./manage.py runserver 0.0.0.0:80>{0}".format(log_file))
            sys.exit(0)
        except:
            pass

    return 0

def stop():
    if os.path.exists(pid_file):
        try:
            with open(pid_file, "r") as pidfp:
                pid = pidfp.read()
            os.killpg(int(pid), signal.SIGKILL)
        except Exception as e:
            print(e.message)
        finally:
            os.remove(pid_file)


if sys.argv[1] == "start":
    sys.exit(start())
elif sys.argv[1] == "stop":
    sys.exit(stop())
elif sys.argv[1] == "restart":
    stop()
    start()

